package com.cxs.shopstore.config;

import com.cxs.shopstore.security.token.RsaUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

/*
 * @Author:cxs
 * @Date:2021/5/11  23:12
 * @Version 1.0
 * jwt配置类
 * */
@Component
@ConfigurationProperties(prefix = "cxs.jwt")
public class JwtPropertiesConfig {
    private String secret;
    private String pubKeyPath;
    private String priKeyPath;
    private Integer expire;
    private PublicKey publicKey;
    private PrivateKey privateKey;

    //日志输出
    private static final Logger logger =  LoggerFactory.getLogger(JwtPropertiesConfig.class);

    @PostConstruct
    public void init(){
        try {
            File pubKey = new File(pubKeyPath);
            File priKey = new File(priKeyPath);
            if(!pubKey.exists() || !priKey.exists()){
                //生成公钥和私钥
                RsaUtils.generateKey(pubKeyPath,priKeyPath,secret);
            }
            //获取公匙和私匙
            this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
        } catch (Exception e) {
            logger.error("初始化公匙和私匙失败！",e);
            throw new RuntimeException();
        }
    }
    //Get & Set

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public String getPubKeyPath() {
        return pubKeyPath;
    }

    public void setPubKeyPath(String pubKeyPath) {
        this.pubKeyPath = pubKeyPath;
    }

    public String getPriKeyPath() {
        return priKeyPath;
    }

    public void setPriKeyPath(String priKeyPath) {
        this.priKeyPath = priKeyPath;
    }

    public Integer getExpire() {
        return expire;
    }

    public void setExpire(Integer expire) {
        this.expire = expire;
    }

    public PublicKey getPublicKey() {
        return publicKey;
    }

    public void setPublicKey(PublicKey publicKey) {
        this.publicKey = publicKey;
    }

    public PrivateKey getPrivateKey() {
        return privateKey;
    }

    public void setPrivateKey(PrivateKey privateKey) {
        this.privateKey = privateKey;
    }

    @Override
    public String toString() {
        return "JwtPropertiesConfig{" +
                "secret='" + secret + '\'' +
                ", pubKeyPath='" + pubKeyPath + '\'' +
                ", priKeyPath='" + priKeyPath + '\'' +
                ", expire=" + expire +
                ", publicKey=" + publicKey +
                ", privateKey=" + privateKey +
                '}';
    }
}

